package cn.sunxiansheng.intelligent.analysis.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.UnsupportedEncodingException;

/**
 * Description: 邮件工具类
 *
 * @Author sun
 * @Create 2025/1/2 18:36
 * @Version 1.0
 */
@Component
public class MailUtil {

    @Resource
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送html邮件，没报错就是发送成功了
     *
     * @param to          收件人
     * @param name        发件人名称
     * @param subject     邮件主题
     * @param htmlContent 邮件内容
     */
    public void sendHtmlMessage(String to, String name, String subject, String htmlContent) throws UnsupportedEncodingException, MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        // 创建邮件发送者地址
        helper.setFrom(new InternetAddress(MimeUtility.encodeText(name) + "<" + from + ">"));
        // 创建邮件发送者地址
        helper.setTo(new InternetAddress(MimeUtility.encodeText("接收方") + "<" + to + ">"));
        // 标题
        helper.setSubject(subject);
        // 第二个参数指定发送的是HTML格式
        helper.setText(htmlContent, true);
        mailSender.send(message);
    }
}